package cn.yuan.client;

import java.net.InetSocketAddress;

import cn.yuan.handler.EchoClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author tao
 */
public class EchoClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(EchoClient.class);

    private final String host;

    private final int port;

    public EchoClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() {

        EventLoopGroup eventLoops = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoops)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host, port))
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new EchoClientHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect().sync();
            future.channel().closeFuture().sync();
        }
        catch (InterruptedException e) {
            LOGGER.error("客户端连接失败", e);
            try {
                eventLoops.shutdownGracefully().sync();
            }
            catch (InterruptedException ex) {
                LOGGER.error("事件循环终止失败", ex);
            }

        }

    }

    public static void main(String[] args) {
        String host;
        int port;
        if (args.length == 0) {
            host = "127.0.0.1";
            port = 8899;
        }
        else if (args.length == 1) {
            host = "127.0.0.1";
            port = Integer.parseInt(args[0]);
        }
        else {
            host = args[0];
            port = Integer.parseInt(args[1]);
        }
        LOGGER.info("客户端连接地址：[{}] : [{}]", host, port);
        new EchoClient(host, port).start();
    }
}
